<?php
/**
 * Created by PhpStorm.
 * User: Acer
 * Date: 2022/7/10
 * Time: 12:02
 */
namespace app\move\service;

use app\move\models\FamilyCardModel;
use app\move\models\IdentityCardModel;
use app\move\models\WxUserModel;
use app\wx\models\UserModel;
use app\wx\service\AuthorizeService;
use think\Db;
use think\Log;

class WxUserService{

    // 用户是否实名认证
    public function is_user_authentication($data){
        $UserModel = new WxUserModel();
        $id_card = $UserModel->where('id',$data['uid'])->value('did');
        return $id_card;
    }
    // 用户实名认证
    public function s_user_authentication($data){
        // 身份证号是否正确
        if(!isIdno($data['people_card_code'])) {
            Log::record("身份证号不正确");
            json_err(-210,['身份证号不正确！']);
        }
        // 身份证实名认证[第三方接口]
        $idenAuthenticationData = $this->s_idenAuthentication($data['people_card_code'],$data['name']);
        if((int)$idenAuthenticationData['respCode'] !== 0000) {
            Log::record("身份证实名认证失败：".$idenAuthenticationData['respMessage']);
            json_err(-210,[$idenAuthenticationData['respMessage']]);
        }
        $IdentityCardModel = new IdentityCardModel();
        // 通过身份证号查询出出生日期
        $birth = strlen($data['people_card_code'])==15 ? ('19' . substr($data['people_card_code'], 6, 6)) : substr($data['people_card_code'], 6, 8);
        $birthday = substr($birth,0,4).'-'. substr($birth,4,2).'-'. substr($birth,6,2);
        // 通过身份证号查询出性别
        $sex= $this->get_sex($data['people_card_code']);

        $userInfo = [
            'name'      =>  $data['name'],
            'id_card'   =>  $data['people_card_code'],
            'birth'     =>  $birthday,
            'sex'       =>  $sex,
            'province'  =>  $idenAuthenticationData['province'],
            'county'    =>  $idenAuthenticationData['county'],
            'city'      =>  $idenAuthenticationData['city'],
            'age'       =>  $idenAuthenticationData['age']
        ];
        $authorizeService = new AuthorizeService();
        $is_user_authentication = $authorizeService->s_identity_code_info($data['people_card_code']);
        // 判断身份证号码是否是本人
        $is_user_authentication =obj_to_arr($is_user_authentication);
        if($is_user_authentication && !empty($is_user_authentication['uid']) && (int)$is_user_authentication['uid'] !== (int)$data['uid']) {
            Log::record("身份信息已被实名");
            json_err(-210,['身份信息已被实名！']);
        }

        if($is_user_authentication){ // 存在身份证编号，更新
            $userInfo['uid']  = $data['uid'];
            $is_save = $IdentityCardModel->save($userInfo,[
                'id_card'   =>  $data['people_card_code'],
            ]);
        }else{
            $IdentityCardModel = new IdentityCardModel();
            $IdentityCarInfo= $IdentityCardModel->where('uid',$data['uid'])->find();
            $IdentityCarInfo= obj_to_arr($IdentityCarInfo);
            // 判断用户是否存在电话号码
            if($IdentityCarInfo && $IdentityCarInfo['mobile']){
                // 更新
                $is_save = $IdentityCardModel->save($userInfo,[
                    'mobile'   =>  $IdentityCarInfo['mobile'],
                    'uid'       =>  $data['uid']
                ]);
            }else{
                // 新增
                $userInfo['uid']  = $data['uid'];
                $installId = $IdentityCardModel->insertGetId($userInfo);
                if(!$installId) {
                    Log::record("认证信息添加失败");
                    json_err(-210,['认证信息添加失败！']);
                }
                $is_save = $installId;
            }
        }
        // 同步更改user表中的did
        $user_authentication = $authorizeService->s_identity_code_info($data['people_card_code']);
        if($user_authentication){
            $UserModel = new UserModel();
            // 绑定user表中did
            $UserModel->save(['did'   =>  $user_authentication['did']],['id'   =>  $data['uid']]);
        }
        return $is_save;
    }

    public function get_sex($idcard) {
        if(empty($idcard)) return null;
        $sexint = (int) substr($idcard, 16, 1);
        return $sexint % 2 === 0 ? 2 : 1;
    }

    public function s_edit_id_card_info($data){
        $FamilyCardModel = new FamilyCardModel();
        $family_card = $FamilyCardModel->where(['pid'=>$data['pid'],'did'=>$data['did']])->find();
        $family_card = obj_to_arr($family_card);
        if($family_card && $family_card['state']==1)  json_err(-210,['信息提交后后无法修改']);
        if(!$family_card || ((time() - strtotime($family_card['creation_time'])) > 7 * 24 * 60 * 60)) {
            Log::record('权益人信息7天后无法修改');
            json_err(-210,['权益人信息7天后无法修改']);
        }

        // 身份证号是否正确
        if(!isIdno($data['people_card_code'])) {
            Log::record('身份证号不正确');
            json_err(-210,['身份证号不正确！']);
        }
        // 身份证实名认证[第三方接口]
        $idenAuthenticationData = $this->s_idenAuthentication($data['people_card_code'],$data['name']);
        if((int)$idenAuthenticationData['respCode'] !== 0000) {
            Log::record('身份证实名认证失败：'.$idenAuthenticationData['respMessage']);
            json_err(-210,[$idenAuthenticationData['respMessage']]);
        }
        // 通过身份证号查询出出生日期
        $birth = strlen($data['people_card_code'])==15 ? ('19' . substr($data['people_card_code'], 6, 6)) : substr($data['people_card_code'], 6, 8);
        $birthday = substr($birth,0,4).'-'. substr($birth,4,2).'-'. substr($birth,6,2);
        // 通过身份证号查询出性别
        $sex= $this->get_sex($data['people_card_code']);
        $userInfo = [
            'name'      =>  $data['name'],
            'id_card'   =>  $data['people_card_code'],
            'birth'     =>  $birthday,
            'sex'       =>  $sex,
            'mobile'    =>  $data['phone'],
            'province'  =>  $idenAuthenticationData['province'],
            'county'    =>  $idenAuthenticationData['county'],
            'city'      =>  $idenAuthenticationData['city'],
            'age'       =>  $idenAuthenticationData['age']
        ];

        // 判断用户是否存在
        $IdentityCardModel = new IdentityCardModel();
        $is_id_user = $IdentityCardModel->where('id_card',$data['people_card_code'])->find();
        $is_id_user = obj_to_arr($is_id_user);
        // 不能自己添加自己
        $myInfo = $IdentityCardModel->where('uid',$data['uid'])->find();
        $myInfo = obj_to_arr($myInfo);
        if($myInfo && !empty($myInfo['did']) &&(int)$is_id_user['did'] == (int)$myInfo['did']) {
            Log::record('不能自己添加自己为亲友');
            json_err(-210,['不能自己添加自己为亲友！']);
        }

        $IdentityCardModel->where('did',$data['did'])->update($userInfo);
        return $data['did'];
    }

    // 添加亲人
    /**
     * @param $data
     * @param null $type
     * @return int|string
     */
    public function s_add_id_card_info($data){
        // 身份证号是否正确
        if(!isIdno($data['people_card_code'])) {
            Log::record("身份证号不正确");
            json_err(-210,['身份证号不正确！']);
        }
        // 身份证实名认证[第三方接口]
        $idenAuthenticationData = $this->s_idenAuthentication($data['people_card_code'],$data['name']);
        if((int)$idenAuthenticationData['respCode'] !== 0000) {
            Log::record("身份证实名认证失败：".$idenAuthenticationData['respMessage']);
            json_err(-210,[$idenAuthenticationData['respMessage']]);
        }
        $IdentityCardModel = new IdentityCardModel();
        // 通过身份证号查询出出生日期
        $birth = strlen($data['people_card_code'])==15 ? ('19' . substr($data['people_card_code'], 6, 6)) : substr($data['people_card_code'], 6, 8);
        $birthday = substr($birth,0,4).'-'. substr($birth,4,2).'-'. substr($birth,6,2);
        // 通过身份证号查询出性别
        $sex= $this->get_sex($data['people_card_code']);
        $userInfo = [
            'name'      =>  $data['name'],
            'id_card'   =>  $data['people_card_code'],
            'birth'     =>  $birthday,
            'sex'       =>  $sex,
            'mobile'    =>  $data['phone'],
            'province'  =>  $idenAuthenticationData['province'],
            'county'    =>  $idenAuthenticationData['county'],
            'city'      =>  $idenAuthenticationData['city'],
            'age'       =>  $idenAuthenticationData['age']
        ];

        $is_id_card = $IdentityCardModel->where('id_card',$data['people_card_code'])->find();
        $is_id_card= obj_to_arr($is_id_card);

      // 用身份证号码判断手机号码是否一致
        if(!empty($data['phone'])){
            if($is_id_card &&!empty($is_id_card['mobile']) && (int)$is_id_card['mobile'] !== (int)$data['phone']) {
                Log::record('电话号码错误，请联系【'.$data['name'].'】！');
                json_err(-210,['电话号码错误，请联系【'.$data['name'].'】！']);
            }
            // 用手机号判断身份证号码是否一致
            $is_mobile = $IdentityCardModel->where('mobile',$data['phone'])->find();
            $is_mobile= obj_to_arr($is_mobile);
            if($is_mobile &&!empty($is_mobile['id_card']) && (int)$is_mobile['id_card'] !== (int)$data['people_card_code'] ) {
                Log::record('信息匹配错误，请联系【'.$data['name'].'】！');
                json_err(-210,['信息匹配错误，请联系【'.$data['name'].'】！']);
            }
        }
        // 判断用户是否存在
//         $is_id_user = $IdentityCardModel->where('id_card',$data['people_card_code'])->where('mobile',$data['phone'])->find();
        $is_id_user = $IdentityCardModel->where('id_card',$data['people_card_code'])->find();
        $is_id_user = obj_to_arr($is_id_user);
        // 不能自己添加自己
        $myInfo = $IdentityCardModel->where('uid',$data['uid'])->find();
        $myInfo = obj_to_arr($myInfo);
        if($myInfo && !empty($myInfo['did']) &&(int)$is_id_user['did'] == (int)$myInfo['did']) {
            Log::record('不能自己添加自己为亲友');
            json_err(-210,['不能自己添加自己为亲友！']);
        }
        if(!$is_id_user) return  $IdentityCardModel->insertGetId($userInfo);
        return $is_id_card['did'];
    }
    // 绑定亲人信息
    public function s_bind_user_family($data,$did){
        // 是否存在绑定
        $FamilyCardModel = new FamilyCardModel();
        $installData =[
            'pid'   =>  $data['pid'],
            'puid'  =>  $data['uid'],
            'did'   =>  $did,
        ];
        $bindInfo = $FamilyCardModel->where($installData)->find(); // 一个人只能绑定一张卡
        if($bindInfo) {
            Log::record('该亲人信息已存在绑定关系');
            json_err(-210,['该亲人信息已存在绑定关系！']);
        }
        $installData['type'] = $data['type'];
        return  $FamilyCardModel->insertGetId($installData);
    }
    // 添加亲人
    public function s_add_user_family($data){
        Db::startTrans();
        try{
            // 是否开启了多卡模式
            if(config('single_card') !== 1){
                $IdentityCardModel = new IdentityCardModel();
                $is_id_card = $IdentityCardModel->where('id_card',$data['people_card_code'])->find();
                $is_id_card= obj_to_arr($is_id_card);
                if($is_id_card){
                    $FamilyCardModel = new FamilyCardModel();
                    $FamilyCardInfo = $FamilyCardModel->where('did',$is_id_card['did'])->value('did');
                    $FamilyCardInfo= obj_to_arr($FamilyCardInfo);
                    if($FamilyCardInfo){ Db::rollback(); json_err(-210,['用户已有卡片，不能重复绑定！']);}
                }
            }
            // 存储用户信息
            $did = $this->s_add_id_card_info($data);
            if($did){
                // 绑定用户信息
              $res = $this->s_bind_user_family($data,$did);
                if($res){
                    Log::record('添加亲人成功');
                    Db::commit();
                    return true;
                }
            }
            Log::record('添加亲人失败，did不存在');
            // 回滚事务
            Db::rollback();
            return false;
        } catch (\Exception $e) {
            Log::record('添加亲人失败，异常了'.$e->getMessage());
            // 回滚事务
            Db::rollback();
        }
    }
    /**
     * 身份证件实名认证[第三方]
     * @param $idCrad   身份证号码
     * @param $name     姓名
     */
    public function s_idenAuthentication($idCrad,$name){
        if(empty($idCrad) || empty($name)) return false;
        $url = config("iden_authentication_api");
        $appcode = config("iden_appCode");
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/x-www-form-urlencoded; charset=UTF-8");
        $res = send_request($url,'POST',[
            'idNo'  =>  $idCrad,
            'name'  =>  $name
        ],$headers);
        $res= (array)json_decode($res);
        return $res;
    }


}
